﻿using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace visinia.SmartEngine.Installer
{
    public class ZipController
    {
        #region Unzip
        public static bool ExtractZip(Stream Stream, string Folder)
        {
            ZipFile zf = null;
            try
            {                
                zf = new ZipFile(Stream);
                foreach (ZipEntry zipEntry in zf)
                {
                    if (zipEntry.IsDirectory)
                        continue;
                    ExtractFile(Folder, zf, zipEntry);
                }
                zf.Close();
            }
            catch
            {
                if (zf != null)                                    
                    zf.Close();                
                return false;
            }            
            return true;
        }

        public static bool ExtractZip(string ZipFilePath, string Folder)
        {
            if (File.Exists(ZipFilePath))
            {
                ZipFile zf = null;
                try
                {
                    zf = new ZipFile(ZipFilePath);
                    foreach (ZipEntry zipEntry in zf)
                    {
                        if (zipEntry.IsDirectory)
                            continue;
                        ExtractFile(Folder, zf, zipEntry);
                    }
                    zf.Close();
                    return true;
                }
                catch
                {
                    if (zf != null)                    
                        zf.Close();                    
                    return false;
                }                
            }
            return true;
        }

        private static void ExtractFile(string outFolder, ZipFile zf, ZipEntry zipEntry)
        {
            String entryFileName = zipEntry.Name;
            byte[] buffer = new byte[4096];
            int intSize = 4096;
            Stream zipStream = zf.GetInputStream(zipEntry);
            String fullZipToPath = Path.Combine(outFolder, entryFileName);
            string directoryName = Path.GetDirectoryName(fullZipToPath);
            if (directoryName.Length > 0)
                Directory.CreateDirectory(directoryName);
            using (FileStream streamWriter = File.Create(fullZipToPath))
            {
                intSize = zipStream.Read(buffer, 0, buffer.Length);
                while (intSize > 0)
                {
                    streamWriter.Write(buffer, 0, intSize);
                    intSize = zipStream.Read(buffer, 0, buffer.Length);
                }
            }
        }
        #endregion
    }
}
